package com.newlink.building.userinfo.activity

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.newlink.building.common_base.base.BaseApplication.Companion.memoryCacheDeviceData
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.base.NL_OnActivityCallback
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_HOME_REFRESH_DEVICE
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.DeviceData
import com.newlink.building.common_base.model.bean.DeviceListRequest
import com.newlink.building.common_base.widget.CustomDialog
import com.newlink.building.common_base.widget.CustomDividerItemDecoration
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.adapter.Module_UserInfo_DeviceManagementAdapter
import com.newlink.building.userinfo.databinding.ActivityDeviceManagementBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_DeviceSettingPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_DeviceSettingContract
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker
import org.greenrobot.eventbus.EventBus

/**
 * Created by xiaodong on 2024/12/13.
 */
class Module_UserInfo_DeviceSettingActivityNL :
    NL_BaseMvpActivity<Module_UserInfo_DeviceSettingContract.View, Module_UserInfo_DeviceSettingContract.Presenter>(),
    Module_UserInfo_DeviceSettingContract.View, View.OnClickListener {

    //当前页数
    private var pageNum = 1

    //每页加载数量
    private var pageLimit = 20
    private lateinit var mBinding: ActivityDeviceManagementBinding
    private var deviceDatas: MutableList<DeviceData> = mutableListOf()
    private var isRefresh = false

    private val mDeviceManagementAdapter: Module_UserInfo_DeviceManagementAdapter by lazy {
        Module_UserInfo_DeviceManagementAdapter()
    }

    override fun attachLayoutRes(): View {
        mBinding = ActivityDeviceManagementBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
    }

    override fun initView() {
        // 设备设置页面初始化时的混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("DeviceSettingActivity", "initView")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom(deviceDatas.hashCode())

        mBinding.titleBar.tvTitleBarCenter.text = resources.getText(R.string.device_setting)
        mBinding.titleBar.ivTitleBarRight.visibility = View.VISIBLE
        mBinding.titleBar.ivTitleBarRight.setImageDrawable(getDrawable(R.drawable.ic_titlebar_add))

        mBinding.titleBar.ivTitleBarRight.setOnClickListener(this)

        mBinding.recyclerView.run {
            adapter = mDeviceManagementAdapter
            addItemDecoration(CustomDividerItemDecoration(1, getColor(R.color.color_bfbfbf)))
            layoutManager = LinearLayoutManager(context)
        }

        mDeviceManagementAdapter.setOnActionClickListener(object :
            Module_UserInfo_DeviceManagementAdapter.OnActionClickListener {
            override fun onEditClick(view: View, position: Int) {
//                startActivity(Intent(this@DeviceSettingActivity, DeviceAddActivity::class.java).apply {
//                    putExtra(Constant.KEY_DEVICE_NAME, deviceDatas[position].devName)
//                    putExtra(Constant.KEY_DEVICE_TYPE, deviceDatas[position].devType)
//                    putExtra(Constant.KEY_DEVICE_MAC, deviceDatas[position].mac)
//                })
                startActivityForResult(
                    Intent(
                        this@Module_UserInfo_DeviceSettingActivityNL,
                        Module_UserInfo_DeviceAddActivityNL::class.java
                    ).apply {
                        putExtra(Base_Constant.KEY_DEVICE_NAME, deviceDatas[position].devName)
                        putExtra(Base_Constant.KEY_DEVICE_TYPE, deviceDatas[position].devType)
                        putExtra(Base_Constant.KEY_DEVICE_MAC, deviceDatas[position].mac)
                    })
            }

            override fun deleteClick(view: View, position: Int) {
                val promptTitle = String.format(
                    getString(R.string.device_setting_ubind),
                    deviceDatas[position].devName
                )
                CustomDialog(this@Module_UserInfo_DeviceSettingActivityNL).setMessage(promptTitle)
                    .setPositiveButton(object : CustomDialog.OnClickListener {
                        override fun onClick(dialog: CustomDialog) {
                            mPresenter?.deleteKitDevice(accessToken, deviceDatas[position].mac)
                            dialog.dismiss()
                        }

                    }).setNegativeButton(object : CustomDialog.OnClickListener {
                        override fun onClick(dialog: CustomDialog) {
                            dialog.dismiss()
                        }

                    }).show()
            }

        })
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_title_bar_right -> {
//                startActivity(Intent(this,DeviceAddActivity::class.java))
                startActivityForResult(Intent(this, Module_UserInfo_DeviceAddActivityNL::class.java))
            }
        }
    }

    fun startActivityForResult(intent: Intent) {
        startActivityForResult(intent, object : NL_OnActivityCallback {
            override fun onActivityResult(resultCode: Int, data: Intent?) {
                when (resultCode) {
                    RESULT_OK -> {
                        isRefresh = true
                        start()
                    }
                }
            }

        })
    }

    override fun createPresenter(): Module_UserInfo_DeviceSettingContract.Presenter {
        return Module_UserInfo_DeviceSettingPresenter()
    }


    override fun start() {
        mPresenter?.getDeviceList(
            DeviceListRequest(accessToken, pageNum, pageLimit, "", null)
        )
    }

    override fun refreshDeviceList(total: Int, data: MutableList<DeviceData>) {
        if (pageNum == 1) {//加载第一页,刷新数据
            mDeviceManagementAdapter.setNewOrAddData(true, data)
            deviceDatas.clear()
            deviceDatas = data
        } else {//不是第一页,添加数据
            deviceDatas.addAll(data)
            mDeviceManagementAdapter.setNewOrAddData(false, data)
        }

        if (deviceDatas.size < total) {//缓存设备条目小于总数量,需要加载更多
            mDeviceManagementAdapter.loadMoreModule.loadMoreComplete()
            mDeviceManagementAdapter.loadMoreModule.isLoadEndMoreGone
        } else {
            mDeviceManagementAdapter.loadMoreModule.loadMoreEnd()
        }
        if (total < pageLimit) {//设备条目数不够一页,不需要加载更多
            mDeviceManagementAdapter.loadMoreModule.loadMoreEnd()
        }
        if (isRefresh) {
            memoryCacheDeviceData(deviceDatas)
            EventBus.getDefault().post(MessageEvent(TYPE_HOME_REFRESH_DEVICE, 0))
            isRefresh = false
        }

    }

    override fun editDeviceResult(success: Boolean) {

    }

    override fun addDeviceResult(success: Boolean) {
    }

    override fun deleteDeviceResult(success: Boolean) {
        showToast(if (success) getString(R.string.default_delete_success) else getString(R.string.default_delete_fail))
        isRefresh = true
        start()
        mDeviceManagementAdapter.notifyDataSetChanged()
    }

}